<?php
// +----------------------------------------------------------------------
// | HkCms 模块商店
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use common\controller\AdminBase;

class Moduleshop extends AdminBase
{
    // 在线模块列表
    public function index()
    {
        if ($this->request->isPost()) {
            $this->redirect('index', $_POST);
        }
        $parameter = array(
            'page' => input(config('paginate.var_page'))? : 1,
        );
        $keyword = input('keyword', '', 'trim');
        $parameter['type'] = $catid = input('catid', 'module', 'trim');
        if (!empty($keyword)) {
            $parameter['keyword'] = $keyword;
        }
        $this->assign('keyword', $keyword);
        $this->assign('catid', $catid);
        if ($this->request->isAjax()) {
            $data = $this->Cloud->appCenter($parameter,'cms/appserver/getList');
            if (false === $data) {
                exit($this->Cloud->getError());
            }
            $data['data'] = $data['list']? : array();
            foreach ($data['data'] as $sign => $rs) {
                $version = db('Module')->where(array('sign' => $rs['mark']))->value('version');
                if ($version && version_compare($version, $rs['version'], '<')) {
                    $data['data'][$sign]['upgrade'] = true;
                    $data['data'][$sign]['newVersion'] = $rs['version'];
                } else {
                    $data['data'][$sign]['upgrade'] = false;
                }
            }
            $page = $this->page($data['page']['total'], $data['page']['paging']);
            $this->assign('Page', $page->show());
            $this->assign('data', $data['data']);
            return $this->fetch('ajax');
        }
        $this->assign('page', $parameter['page']);
        return $this->fetch();
    }

    /**
     * 在线栏目列表
     * @return mixed
     */
    public function catList()
    {
        if ($this->request->isAjax()) {
            $data = $this->Cloud->appCenter(['type'=>'module'],'cms/appserver/category');
            if (false === $data) {
                exit($this->Cloud->getError());
            }
            $this->assign('data', $data);
            $this->assign('catid', input('catid'));
            return $this->fetch('category');
        }
    }

    /**
     * 云端模块下载安装
     * @return mixed
     */
    public function install()
    {
        $id = input('id', '', 'trim');
        $mark = input('mark', '', 'trim');
        $install_version = input('version', '', 'trim');
        if (empty($id) || empty($mark)) {
            $this->error('请选择需要安装的模版！');
        }
        $this->assign('stepUrl', url('public_step_1', array('id' => $id,'mark'=>$mark,'version'=>$install_version)));
        $this->assign('sign', $id);
        return $this->fetch();
    }

    /**
     * 下载
     */
    public function public_step_1()
    {
        if (\libs\system\RBAC::authenticate('install') !== true) {
            $this->errors('您没有该项权限！');
        }
        $mark = input('mark', '', 'trim');
        $id = input('id', '', 'trim');
        $install_version = input('version', '', 'trim');
        if (empty($id) || empty($mark)) {
            $this->error('请选择需要安装的模版！');
        }
        $cache = cache('Cloud');
        if (!empty($cache)) {
            $this->error('已经有任务在执行，请稍后！');
        }
        //帐号权限检测
        if ($this->Cloud->competence() == false) {
            $this->errors($this->Cloud->getError());
        }

        $path = APP_PATH . $mark;
        //检查是否有同样的插件目录存在
        if (file_exists($path)) {
            $version = db('Module')->where(array('sign' => $mark))->value('version');
            if ($version==$install_version) {
                $this->errors("目录：{$path} 已经存在，无法安装在同一目录！");
            } else {
                // 先卸载旧的版本，再安装新的版本
                $this->Module->uninstall($mark);
            }
        }
        //获取下载地址
        $packageUrl = $this->Cloud->appCenter(['id'=>$id],'cms/appserver/getPackage');
        if (empty($packageUrl['url'])) {
            $this->errors($this->Cloud->getError());
        } else {
            cache('Cloud', ['mark'=>$mark,'url'=>$packageUrl['url']], 3600);
        }
        //开始下载
        if ($this->CloudDownload->storageFile($packageUrl['url']) !== true) {
            $this->errors($this->CloudDownload->getError());
        }
        $this->success('文件下载完毕！', url('public_step_2', array('package' => $packageUrl['url'])));
    }

    //移动目录到模块
    public function public_step_2()
    {
        if (\libs\system\RBAC::authenticate('install') !== true) {
            $this->errors('您没有该项权限！');
        }
        $data = cache('Cloud');
        if (empty($data)) {
            $this->errors('获取不到需要安装的模块信息缓存！');
        }
        $packageUrl = input('package');
        if (empty($packageUrl)) {
            $this->errors('package参数为空！');
        }
        //临时目录名
        $tmp = $this->CloudDownload->getTempFile($packageUrl);
        //模块安装目录
        $modulePath = APP_PATH . "{$data['mark']}/";
        if ($this->CloudDownload->movedFile($tmp, $modulePath, $packageUrl) !== true) {
            $this->errors($this->CloudDownload->getError());
        }
        $this->success('移动文件到模块目录中，等待安装！', url('public_step_3', array('module' => $data['mark'])));
    }

    /**
     * 安装模块
     */
    public function public_step_3()
    {
        if (\Libs\System\RBAC::authenticate('install') !== true) {
            $this->errors('您没有该项权限！');
        }
        $module = input('module');

        // 执行安装
        cache('Cloud', NULL);
        if ($this->Module->install($module)) {
            HkCMS()->Dir->delDir(APP_PATH . "{$module}/install/");
            $this->success('模块安装成功！');
        } else {
            $error = $this->Module->error;
            //删除目录
            HkCMS()->Dir->delDir(APP_PATH . $module);
            $this->error($error ? $error : '模块安装失败！');
        }
    }

    /**
     * 获取模块使用说明
     */
    public function public_explanation()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('缺少参数！');
        }
        $parameter = array(
            'id' => $id
        );
        $data = $this->Cloud->appCenter($parameter,'cms/appserver/showInfo');
        if (false === $data) {
            $this->error($this->Cloud->getError());
        }
        $this->ajaxReturn(array('status' => true, 'data' => $data));
    }

    /**
     * 模块升级页
     * @return mixed
     */
    public function upgrade()
    {
        $sign = input('mark', '', 'trim');
        $id = input('id', '', 'trim');
        if (empty($sign) || empty($id)) {
            $this->error('请选择需要升级的模块！');
        }
        $cache = cache('Cloud');
        if (!empty($cache)) {
            $this->error('已经有任务在执行，请稍后！');
        }
        //帐号权限检测
        if ($this->Cloud->competence() == false) {
            $this->error($this->Cloud->getError());
        }
        $data = $this->Cloud->appCenter(['id'=>$id],'cms/appserver/showInfo');
        if (false === $data) {
            $this->error($this->Cloud->getError());
        } else {
            $version = db('Addons')->field('version')->where(array('sign' => $data['mark']))->find();
            if ($version && !version_compare($version['version'], $data['version'], '<')) {
                $this->error('该模块无需升级！');
            }
            cache('Cloud', $data, 3600);
        }
        $this->assign('stepUrl', url('public_upgrade_1'));
        return $this->fetch();
    }

    public function public_upgrade_1()
    {
        if (\libs\system\RBAC::authenticate('upgrade') !== true) {
            $this->errors('您没有该项权限！');
        }
        $data = cache('Cloud');
        if (empty($data)) {
            $this->errors('获取不到需要升级的模块信息缓存！');
        }
        $config = db('module')->where(array('sign' => $data['mark']))->find();
        if (empty($config)) {
            $this->errors("没有安装该模块无法升级！");
        }

        //获取下载地址
        $packageUrl = $this->Cloud->appCenter(['id'=>$data['id']],'cms/appserver/getPackage');
        if (empty($packageUrl['url'])) {
            $this->errors($this->Cloud->getError());
        } else {
            cache('Cloud', ['mark'=>$data['mark'],'url'=>$packageUrl['url']], 3600);
        }
        //开始下载
        if ($this->CloudDownload->storageFile($packageUrl['url']) !== true) {
            $this->errors($this->CloudDownload->getError());
        }
        $this->success('升级包文件下载完毕！', url('public_upgrade_2', array('package' => $packageUrl['url'])));
    }

    public function public_upgrade_2()
    {
        if (\libs\system\RBAC::authenticate('upgrade') !== true) {
            $this->errors('您没有该项权限！');
        }
        $data = cache('Cloud');
        if (empty($data)) {
            $this->errors('获取不到需要升级的插件信息缓存！');
        }
        $packageUrl = input('package');
        if (empty($packageUrl)) {
            $this->errors('package参数为空！');
        }

        // 卸载旧版本
        $this->Module->uninstall($data['mark']);
        $tmp = $this->CloudDownload->getTempFile($packageUrl);
        //模块安装目录
        $modulePath = APP_PATH . "{$data['mark']}/";
        if ($this->CloudDownload->movedFile($tmp, $modulePath, $packageUrl) !== true) {
            $this->errors($this->CloudDownload->getError());
        }
        $this->success('移动文件到模块目录中，等待安装！', url('public_upgrade_3', array('module' => $data['mark'])));
    }

    public function public_upgrade_3() {
        // 执行安装
        if (\Libs\System\RBAC::authenticate('install') !== true) {
            $this->errors('您没有该项权限！');
        }
        $module = input('module');

        // 执行安装
        cache('Cloud', NULL);
        if ($this->Module->install($module)) {
            HkCMS()->Dir->delDir(APP_PATH . "{$module}/install/");
            $this->success('模块安装成功！');
        } else {
            $error = $this->Module->error;
            //删除目录
            HkCMS()->Dir->delDir(APP_PATH . $module);
            $this->error($error ? $error : '模块安装失败！');
        }
    }

    /**
     *
     * @param string $message
     * @param string $jumpUrl
     * @param bool $ajax
     */
    protected function errors($message = '', $jumpUrl = '', $ajax = false)
    {
        cache('Cloud', NULL);
        $this->error($message, $jumpUrl);
    }
}